<!-- 采购单生成 -->
<template>
  <div>
    <cus-search style="padding-bottom: 0;">
      <cus-search-item>
        <Form :model="form" ref="formValidate" @keydown.native.enter.prevent="onInit">
          <FormItem label="采购单号" :label-width="80" class="mr_48 mb_20" prop="billNo">
            <Input v-model="form.billNo" clearable maxlength="20" placeholder="请输入采购单号" />
          </FormItem>
          <FormItem label="供应商" :label-width="60" class="mr_48 mb_20" prop="supplyName">
            <Select size="large" v-model="form.supplyName" clearable style="width: 200px">
              <Option v-for="item in supplyTree" :value="item.name" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="创建日期" :label-width="80" class="mr_48 mb_20">
            <DatePicker type="daterange" @on-change="sDaterangeChange" ref="formDate1" placeholder="开始日期 - 结束日期"
              style="width: 200px" />
          </FormItem>
          <FormItem label="供应日期" :label-width="80" class="mr_48 mb_20">
            <DatePicker type="date" @on-change="sDateChange" ref="formDate2" placeholder="开始日期" style="width: 200px" />
          </FormItem>
          <cusButton class="mr_20 mb_20" type="primary" @onClick="postApiPurchasingPoorderlistApi()">查询</cusButton>
          <cusButton class="mr_20 mb_20" type="primary" @onClick="reset()">重置</cusButton>
        </Form>
      </cus-search-item>
    </cus-search>
    <cus-card class="cus_cardBox" :showTitle="false">
      <div class="btnBox">
        <cusButton type="primary" @onClick="onAdd()" style="width: 150px" v-if="status != 1">添加</cusButton>
      </div>
      <cusTable border highlight-row :loading="form.loading" :columns="columns" :data="data" :size="vuex_config.tableSize"
        :bottomClass="['cus-page', 'cus_operBox']">
        <template slot-scope="{ row, index }" slot="operation">
          <div class="flex">
            <cus-button type="text" size="small" :style="{ color: '#1E6FFF' }" style="padding: 0 5px"
              @onClick="onShow(row)">
              <Icon type="ios-search" size="4" style="margin: 2px 3px 0 0" />
              <span>查看</span>
            </cus-button>
            <!-- <cus-button type="text" size="small" :style="{ color: '#1E6FFF' }" style="padding: 0 5px"
              v-if="status == 1 || status == 5" @onClick="onQcode(row)">
              <Icon type="ios-search" size="4" style="margin: 2px 3px 0 0" />
              <span>二维码</span>
            </cus-button> -->
            <cus-button type="text" size="small" v-if="status == 1 || status == 5" :style="{ color: '#1E6FFF' }"
              style="padding: 0 5px" @onClick="downTableExcel(row)">
              <Icon type="ios-download-outline" size="4" style="margin: 2px 3px 0 0" />
              <span>导出</span>
            </cus-button>
          </div>
        </template>
      </cusTable>
      <div class="cus_page">
        <cus-page :data="pages" class="mt_20" @pageChange="postApiPurchasingPoorderlistApi"></cus-page>
      </div>
    </cus-card>
    <!--底部返回-->
    <div class="cus_operBox" style="z-index: 1001;width: calc(100% - 250px)">
      <Button type="error" class="mr_20" @click="onReturn">返回</Button>
    </div>
    <!--二维码展示-->
    <Modal v-model="modal" title="二维码">
      <div class="permission">
        <!-- <span v-if="qcode.length>1">滚动查看更多</span> -->
        <img v-for="(item, index) in qcode" :key="index" :src="item" alt="二维码" style="width: 100%; height: 100%">
        <!-- <img :src="qcode" alt="二维码" style="width: 100%; height: 100%" /> -->
      </div>
      <div slot="footer">
        <slot name="footer">
          <div class="modal-footer">
            <cus-button size="small" class="mr_2" @onClick="modal = false">取消</cus-button>
            <cus-button type="primary" size="small" @onClick="onOk">下载二维码</cus-button>
          </div>
        </slot>
      </div>
      <Spin size="large" fix v-if="modelLoading"></Spin>
    </Modal>
  </div>
</template>
<script>
import {
  postApiPurchasingPoorderlist,
  postApiPurchasingPoorderlistQrcode,
  postApiPurchasingInportPoOrderExcel,
  getApiPurchasingSupplierName,
} from "@/api/business/manager";
import axios from "axios";
export default {
  name: "purchaseMangement",
  components: {},
  data() {
    return {
      form: {
        supplyName: "", // 供应商名称
        billNo: "", // 单号
        startDate: "", // 开始时间
        stopDate: "", // 结束时间
        deliveDate: "", // 供应日期
        loading: false,
      },
      qcode: "", //二维码
      modal: false, //二维码展示模态框
      ruleValidate: {},
      // 表头
      columns: [
        {
          title: "序号",
          type: "index",
          align: "center",
          width: 70,
        },
        {
          title: "采购单号",
          key: "billNo",
          align: "center",
          minWidth: 125,
        },
        // {
        //   title: "采购计划名称",
        //   key: "supplierPurchasingName",
        //   align: "center",
        //   minWidth: 125,
        // },
        {
          title: "供应商",
          key: "supplyName",
          align: "center",
          minWidth: 125,
        },
        {
          title: "创建人",
          key: "createByName",
          align: "center",
          minWidth: 125,
        },
        {
          title: "创建时间",
          align: "center",
          minWidth: 125,
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                `${new Date(params.row.createTime).Format("yyyy-MM-dd")}`
              ),
            ]);
          },
        },
        {
          title: "供应日期",
          align: "center",
          minWidth: 125,
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                `${new Date(params.row.deliveDate).Format("yyyy-MM-dd")}`
              ),
            ]);
          },
        },
        {
          title: "供应星期",
          key: "week",
          align: "center",
          minWidth: 125,
        },
        {
          title: "操作",
          fixed: "right", // 右侧固定
          slot: "operation",
          align: "center",
          minWidth: 175,
        },
      ],
      data: [], // 表格列表
      supplyTree: [], // 供应商列表
      // 分页
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      tableHeight: 0,
      modelLoading: false, //查看二维码loading
      status: "",
    };
  },
  mounted() {
    setTimeout(() => {
      this.tableHeight = window.innerHeight - 430; // 表格自适应高度
    }, 100);
    window.addEventListener("resize", this.tableHeightChange, true);
    this.status = this.$route.query.status;
    this.onInit();
  },
  destroyed() {
    window.removeEventListener("resize", this.tableHeightChange, true);
  },
  methods: {
    tableHeightChange() {
      this.tableHeight = 0;
      setTimeout(() => {
        this.tableHeight = window.innerHeight - 430; // 表格自适应高度
      }, 100);
    },
    onInit() {
      this.getApiPurchasingSupplierNameApi();
      this.postApiPurchasingPoorderlistApi();
    },
    reset() {
      this.$refs["formValidate"].resetFields();
      console.log();
      this.$refs.formDate1.handleClear(); //清空时间
      this.$refs.formDate2.handleClear(); //清空时间
      // 时间清空后有延时，利用nextTick将刷新后置
      console.log('重置后的表单验证', this.form);
      this.$nextTick(() => {
        this.onInit();
      })

    },
    // 日期时间组件
    sDaterangeChange(v) {
      console.log('时间改变');
      this.form.startDate = v[0];
      this.form.stopDate = v[1];
    },
    sDateChange(date) {
      this.form.deliveDate = date;
    },
    // 添加采购单
    onAdd() {
      this.$router.push({
        name: "添加采购单",
        query: {
          purchasingPlanId: this.$route.query.id, //采购计划id
          status: this.$route.query.status,
        },
      });
    },
    // 查看
    onShow(row) {
      this.$router.push({
        //添加采购单页面
        path: "/addPurchase/addPurchase",
        query: {
          interId: row.id, // 查看采购计划id
          supplyName: row.supplyName, // 供应商名称
          supplyId: row.supplyId, // 供应商id
          billNo: row.billNo, // 采购单号
          deliveDate: new Date(row.deliveDate).Format("yyyy-MM-dd"), // 供应时间
          week: row.week, // 日期
          status: this.status, //状态
        },
      });
    },
    // 查看二维码
    onQcode(row) {
      this.modal = true;
      this.postApiPurchasingPoorderlistQrcodeApi(row.id);
    },
    // 导出Excel采购计划
    downTableExcel(row) {
      this.postApiPurchasingInportPoOrderExcelApi(row.id);
    },
    // 返回采购单查询
    onReturn() {
      this.$router.push("/view/collectingMaterials/purchasingLnquiry");
    },
    // 创建跨域请求
    async getImage(url) {
      const { data } = await axios({
        method: "GET",
        url: url,
        responseType: "blob",
      });
      console.log('data',data);
      return data;
    },
    // 获取链接后的地址
    GetUrlRelativePath(url) {
      var arrUrl = url.split("//");
      var start = arrUrl[1].indexOf("/");
      var relUrl = arrUrl[1].substring(start); //stop省略，截取从start开始到结尾的所有字符
      if (relUrl.indexOf("?") != -1) {
        relUrl = relUrl.split("?")[0];
      }
      return relUrl;
    },
    downloadUrlFile(urlList, fileName = new Date().valueOf()) {
      // urlList.forEach((url) => {
      //   const url2 = url.replace(/\\/g, "/");
      //   console.log(url2)
      //   const xhr = new XMLHttpRequest();
      //   xhr.open("GET", url2, true);
      //   xhr.he
      //   xhr.responseType = "blob";
      //   //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
      //   // 为了避免大文件影响用户体验，建议加loading
      //   xhr.onload = () => {
      //     if (xhr.status === 200) {
      //       var blob = xhr.response;
      //       const urlObject = window.URL || window.webkitURL || window;
      //       const export_blob = new Blob([blob], { type: "image/jpeg" });
      //       //createElementNS() 方法可创建带有指定命名空间的元素节点。此方法可返回一个 Element 对象。
      //       const save_link = document.createElementNS("a");
      //       save_link.href = urlObject.createObjectURL(export_blob);
      //       let type = blob.type.split("/")[1] || "";
      //       save_link.download = fileName + "." + type;
      //       save_link.click();
      //     }
      //   };
      //   xhr.send();
      // });
      urlList.forEach((file) => {
        let url = this.GetUrlRelativePath(file);
        console.log('调取接口返回地址', url);
        this.getImage(url).then((res) => {
          console.log(res);
          const myBlob = new Blob([res], { type: "image/jpeg" });
          const link = document.createElement("a");
          link.href = URL.createObjectURL(myBlob);
          link.download = fileName;
          link.click();
          link.remove();
          URL.revokeObjectURL(link.href);
        });
      });
      // console.log('地址',file);
      // let url = this.GetUrlRelativePath(file);
      // console.log('调取接口返回地址',url);
      // this.getImage(url).then((res) => {
      //   console.log(res);
      //   const myBlob = new Blob([res], { type: "image/jpeg" });
      //   const link = document.createElement("a");
      //   link.href = URL.createObjectURL(myBlob);
      //   link.download = fileName;
      //   link.click();
      //   link.remove();
      //   URL.revokeObjectURL(link.href);
      // });
    },
    // 下载二维码
    onOk() {
      this.downloadUrlFile(this.qcode);
    },

    // 采购单管理列表数据--------------接口
    postApiPurchasingPoorderlistApi() {
      this.form.loading = true;
      return new Promise((resolve) => {
        let params = {
          supplyName: this.form.supplyName, //供应商
          purchasingPlanId: this.$route.query.id, //采购单id
          billNo: this.form.billNo, //单号
          startDate: this.form.startDate, //开始时间
          stopDate: this.form.stopDate, //结束时间
          deliveDate: this.form.deliveDate, //供应时间
          size: this.pages.pageSize,
          current: this.pages.page,
        };
        postApiPurchasingPoorderlist(params).then((res) => {
          this.form.loading = false;
          if (res.retCode == 2000) {
            this.data = res.data.records;
            this.pages.pageTotal = res.data.total;
            resolve();
          }
        });
      });
    },
    // 查看二维码----------------------接口
    postApiPurchasingPoorderlistQrcodeApi(id) {
      this.modelLoading = true;
      return new Promise((resolve) => {
        let params = {
          poOrderId: id,
        };
        postApiPurchasingPoorderlistQrcode(params).then((res) => {
          this.modelLoading = false;
          if (res.retCode == 2000) {
            this.qcode = res.data;
            console.log(this.qcode);
            resolve();
          }
        });
      });
    },
    // 导出Excel-----------------------------接口
    postApiPurchasingInportPoOrderExcelApi(id) {
      return new Promise((resolve) => {
        postApiPurchasingInportPoOrderExcel({ interId: id }).then((res) => {
          if (res.retCode == 2000) {
            window.location.href = res.data;
            resolve();
          }
        });
      });
    },
    // 供应商名称-----------------------接口
    getApiPurchasingSupplierNameApi() {
      return new Promise((resolve) => {
        getApiPurchasingSupplierName().then((res) => {
          if (res.retCode == 2000) {
            this.supplyTree = res.data;
            resolve();
          }
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.btnBox {
  padding-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.permission {
  /*height: 300px;*/
  max-height: 420px;
  // border: 1px solid #dcdee2;
  overflow-y: auto;
  overflow-x: hidden;
  // border-radius: 2px;
  // padding: 0 0 0 10px;
}

.permission::-webkit-scrollbar {
  display: none;
}
</style>
